import { defineEventHandler, getQuery } from 'h3'
import redis from '../util/redis'
import { recordLog } from '../util/log'

// GET /api/yangmao?key=yourkey
export default defineEventHandler(async (event) => {
  try {
    const q = getQuery(event) as any
    const key = q?.key ?? ''

    try {
      if (key && typeof key === 'string') {
        const value = await (redis as any).get(`ym:${key}`)
        await recordLog(event as any, { message: `yangmao: get key=${key} result=${value ? 'found' : 'notfound'}`, userId: 0 })
        if (value === null) {
          event.node.res.statusCode = 404
          return { status: 404, message: 'not found' }
        }
        let obj = null
        try {
          obj = JSON.parse(value)
        } catch (e) {
          obj = { raw: value }
        }
        return { status: 'ok', key, data: obj }
      } else {
        // list keys (public)
        const keys: string[] = await (redis as any).keys('ym:*')
        const list = (keys || []).map((k) => k.replace(/^ym:/, ''))
        await recordLog(event as any, { message: `yangmao: list keys count=${list.length}`, userId: 0 })
        return { status: 'ok', keys: list }
      }
    } catch (err: any) {
      event.node.res.statusCode = 500
      await recordLog(event as any, { message: `yangmao: redis failed ${String(err)}`, userId: 0 })
      return { status: 500, message: 'redis failed', error: String(err) }
    }
  } catch (err: any) {
    event.node.res.statusCode = 500
    await recordLog(event as any, { message: `yangmao: internal error ${String(err)}`, userId: 0 })
    return { status: 500, message: 'internal error', error: String(err) }
  }
})
